package com.hg.chapter83.service.impl;

import com.hg.chapter83.entity.Student;
import com.hg.chapter83.repository.StudentRepository;
import com.hg.chapter83.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepository studentRepository;

    @Override
    //默认没有开启事务 出现异常没有回滚
    public void addStudentWithoutTransactional(){
        Student student=new Student(null,"WithoutTransactional",20,"WithoutTransactional");
        studentRepository.save(student);
        throw new IllegalArgumentException("测试");
    }

    @Override
    //出现异常回滚
    @Transactional(rollbackFor = {IllegalArgumentException.class})
    public void addStudentWithTransactionalRollback() throws Exception {
        Student student=new Student(null,"Rollback",20,"Rollback");
        studentRepository.save(student);
        throw new IllegalArgumentException("测试");
    }

    @Override
    //没有开启事务回滚
    @Transactional(noRollbackFor = {IllegalArgumentException.class})
    public void addStudentWithTransactionalNoRollback() {
        Student student=new Student(null,"NoRollback",20,"NoRollback");
        studentRepository.save(student);
        throw new IllegalArgumentException("测试");
    }
}
